package com.mikao.controller;

import com.mikao.dto.bo.*;
import com.mikao.dto.vo.*;
import com.mikao.service.UserService;
import com.mikao.util.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author KennyDavid
 */

@Api(description = "用户管理")
@RestController
@RequestMapping("/user")
@Scope("prototype")
@Validated
@Slf4j
public class UserController extends BaseController {

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "登录，写入用户信息")
    @PostMapping("/login")
    public BaseResult<UserVo> login(@ApiParam(value = "用户表单") @RequestBody @Validated({UserBo.Post.class}) UserBo userBo, BindingResult bindingResult) {
        return userService.login(userBo);
    }

    @ApiOperation("获取短信验证码")
    @GetMapping("/auth/getVerifyCode")
    public BaseResult getVerifyCode(@ApiParam(value = "电话", required = true) @RequestParam String mobile) {
        return userService.getVerifyCode(mobile);
    }

    @ApiOperation("绑定手机号")
    @PostMapping("/auth/bindPhone")
    public BaseResult bindPhone(@ApiParam(value = "电话") @RequestBody PhoneForm phoneForm) {
        return userService.bindPhone(phoneForm, getUserId());
    }

    @ApiOperation(value = "商城首页")
    @GetMapping("/index")
    public BaseResult<IndexDto> index() {
        return userService.index();
    }

    @ApiOperation(value = "我的")
    @GetMapping("/auth/myInfo")
    public BaseResult<UserVo> myInfo() {
        return userService.myInfo(getUserId());
    }

    @ApiOperation(value = "修改个人信息")
    @PostMapping("/auth/changeMyInfo")
    public BaseResult changeMyInfo(@RequestBody MyInfoForm myInfoForm) {
        return userService.changeMyInfo(getUserId(), myInfoForm);
    }

    @ApiOperation(value = "积分明细")
    @GetMapping("/auth/pointDetail")
    public BaseResult<List<PointDto>> pointDetail(@ApiParam(value = "收支类型 1收入 0支出", required = true) @RequestParam Integer type) {
        return userService.pointDetail(getUserId(), type);
    }

    @ApiOperation(value = "领取优惠券")
    @PostMapping("/auth/getTicket")
    public BaseResult getTicket(@ApiParam(value = "优惠券表单", required = true) @RequestBody TicketForm ticketForm) {
        return userService.getTicket(getUserId(), ticketForm);
    }

    @ApiOperation(value = "个人中心-我的订单列表")
    @GetMapping("/auth/getMyOrder")
    public BaseResult<List<OrderDto>> getMyOrder(@ApiParam(value = "订单状态（1待付款 2待发货 3待收货 4待评价 5已完成）", required = false) @RequestParam(required = false) Integer type,
                                                 @ApiParam(value = "最后一条数据的创建时间", required = false) @RequestParam(required = false) Date createTime,
                                                 @ApiParam(value = "消息总条数") @RequestParam(required = false, defaultValue = "10") int size) {
        return userService.getMyOrder(getUserId(), type, createTime, size);
    }

    @ApiOperation(value = "获取用户token")
    @GetMapping("/getToken")
    public BaseResult<String> getToken(@ApiParam(value = "用户ID") @RequestParam Long id) {
        return userService.getToken(id);
    }

    @ApiOperation(value = "订单详情")
    @GetMapping("/auth/getOrderDetail")
    public BaseResult<OrderDetailDto> getOrderDetail(@ApiParam(value = "订单ID") @RequestParam Long id) {
        return userService.getOrderDetail(id);
    }

    @ApiOperation("确认收货")
    @PostMapping("/auth/sureOrder")
    public BaseResult sureOrder(@ApiParam(value = "确认收货表单") @RequestBody SureOrderForm sureOrderForm) {
        return userService.sureOrder(getUserId(), sureOrderForm);
    }

    @ApiOperation(value = "我的收货地址列表")
    @GetMapping("/auth/getMyAddress")
    public BaseResult<List<AddressDto>> getMyAddress() {
        return userService.getMyAddress(getUserId());
    }

    @ApiOperation(value = "添加收货地址")
    @PostMapping("/auth/addMyAddress")
    public BaseResult addMyAddress(@RequestBody AddressForm addressForm) {
        return userService.addMyAddress(getUserId(), addressForm);
    }

    @ApiOperation(value = "设置地址为默认地址")
    @PostMapping("/auth/setAddress")
    public BaseResult setAddress(@RequestBody AddressSelect addressSelect) {
        return userService.setAddress(addressSelect);
    }

    @ApiOperation(value = "删除地址")
    @PostMapping("/auth/deleteAddress")
    public BaseResult deleteAddress(@RequestBody AddressSelect addressSelect) {
        return userService.deleteAddress(addressSelect);
    }

    @ApiModelProperty(value = "微信授权校验")
    @GetMapping("/wechat")
    public String check(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("GBK");
        String echostr = req.getParameter("echostr");
        PrintWriter pw = null;
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pw.write(echostr);
        pw.flush();
        pw.close();
        return "wechat";
    }

    @ApiOperation("支付")
    @PostMapping("/auth/pay")
    public BaseResult pay(@ApiParam(value = "支付表单") @RequestBody PayForm payForm) {

        return userService.pay(getUserId(), payForm);
    }

    @ApiOperation("支付树苗")
    @PostMapping("/auth/payTree")
    public BaseResult payTree(@ApiParam(value = "支付表单") @RequestBody PayForm payForm) {
        return userService.payTree(getUserId(), payForm);
    }

    @ApiOperation("添加银行卡/修改银行卡")
    @PostMapping("/auth/addBankCard")
    public BaseResult addBankCard(@ApiParam(value = "银行卡表单") @RequestBody BankCardForm bankCardForm) {
        return userService.addBankCard(getUserId(), bankCardForm);
    }

    @ApiOperation("提现申请")
    @PostMapping("/auth/withdraw")
    public BaseResult withdraw(@ApiParam(value = "提现金额") @RequestBody WithdrawForm withdrawForm) {
        return userService.withdraw(getUserId(), withdrawForm);
    }

    @ApiOperation("充值余额")
    @PostMapping("/auth/charge")
    public BaseResult charge(@ApiParam(value = "充值表单 订单号默认传0") @RequestBody PayForm payForm) {
        return userService.charge(getUserId(), payForm);
    }
    @ApiOperation("支付成功-微信回调增加用户金额")
    @PostMapping("/addMoney")
    public String addMoney() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("微信回调了");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            log.info("微信支付通知结果：" + result);
            Map<String, String> map = null;
            String resXml = "";

            /*
             * 解析微信通知返回的信息
             */
            map = WXPayUtil.xmlToMap(result);


            System.out.println("=========:" + result);
            // 若支付成功，则告知微信服务器收到通知
            if (map.get("return_code").equals("SUCCESS")) {
                if (map.get("result_code").equals("SUCCESS")) {
                    log.info("微信支付-签名验证成功");
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    //业务处理开始
                    String out_trade_no = map.get("out_trade_no");
                    String total_amount = map.get("total_fee");
                    //业务处理结束
                    userService.doWxTypeBy1(out_trade_no, total_amount);
                }
                return resXml;
            } else {
                return "failure";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "e";
        }
    }

    @ApiOperation("微信回调增加用户金额")
    @PostMapping("/addMoneys")
    public void addMoneys(@ApiParam(value = "类型") @RequestParam String type,@ApiParam(value = "类型") @RequestParam String types) {
         userService.doWxTypeBy1(type,types);
    }

    @ApiOperation("资金明细")
    @GetMapping("/auth/moneyDetail")
    public BaseResult<List<MoneyDetailDto>> moneyDetail(@ApiParam(value = "类型") @RequestParam Integer type) {
        return userService.moneyDetail(getUserId(), type);
    }

    @ApiOperation("退款")
    @PostMapping("/wxBack")
    public BaseResult wxBack(@ApiParam(value = "退款表单") @RequestBody BackForm backForm) {
        return userService.wxBack(backForm);
    }

}
